﻿using System.Collections.Concurrent;
using System.Threading;

namespace Sprout.Core.Utils
{
    /// <summary>
    /// 上下文
    /// </summary>
    public static class CallContext
    {
        static ConcurrentDictionary<string, AsyncLocal<object>> state = new ConcurrentDictionary<string, AsyncLocal<object>>();
        static readonly object lockObj = new object();
        /// <summary>
        /// 设置上下文
        /// </summary>
        /// <param name="key">上下文KEY</param>
        /// <param name="data">值</param>
        public static void SetData(string key, object data)
        {
            lock (lockObj)
            {
                if (data != null)
                {
                    if (state.ContainsKey(key) == false)
                    {
                        var local = new AsyncLocal<object>();
                        local.Value = data;
                        state.TryAdd(key, local);
                    }
                }
                else
                {
                    if (state.ContainsKey(key))
                    {
                        var local = new AsyncLocal<object>();
                        state.TryRemove(key, out local);
                    }
                }
            }
        }
        /// <summary>
        /// 获取上下文的值
        /// </summary>
        /// <param name="key">上下文KEY</param>
        /// <returns></returns>
        public static object GetData(string key)
        {
            if (state.ContainsKey(key))
            {
                var local = state[key];
                return local.Value;
            }
            return null;
        }
    }
}
